package com.softeem.service.impl;

import com.softeem.bean.Book;
import com.softeem.bean.CartItem;
import com.softeem.dao.BookDao;
import com.softeem.dao.CartItemDao;
import com.softeem.dao.OrderDao;
import com.softeem.dao.OrderItemDao;
import com.softeem.dao.impl.BookDaoImpl;
import com.softeem.dao.impl.CartItemDaoImpl;
import com.softeem.dao.impl.OrderDaoImpl;
import com.softeem.dao.impl.OrderItemDaoImpl;
import com.softeem.service.OrderService;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
//业务层
public class OrderServiceImpl implements OrderService {
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private OrderDao orderDao = new OrderDaoImpl();
    private CartItemDao cartItemDao = new CartItemDaoImpl() ;
    private BookDao bookDao = new BookDaoImpl();

    // 需要事务
    @Override
    public String createOrder(List<Integer> cartIdList, Integer userId)throws SQLException {
        //开启事务
        List<CartItem> cartList = new ArrayList<>();
        //循环查询cartItem对象
        for (Integer id : cartIdList) {
            //将查询出来的cartItem对象保存到list集合中
            cartList.add(cartItemDao.findById(id));
        }

        Double totalPrice = 0.0 ;//此变量用于保存所有商品价格总和
        for (CartItem cartItem : cartList) {
            totalPrice += cartItem.getTotalPrice();//求出所有商品的总和
        }

        //创建订单成功后,返回此订单编号
        String orderId = orderDao.saveOrder(totalPrice, userId);

        //int i = 10 / 0;

        //循环创建订单项
        for (CartItem cartItem : cartList) {
            orderItemDao.saveOrderItem(cartItem , orderId);//创建订单项目

            //通过商品名称与价格 , 查询出book对象
            Book book = bookDao.queryBookByNameAndPrice(cartItem.getName() , cartItem.getPrice());

            book.setSales( book.getSales() + cartItem.getCount());//销量增加
            book.setStock( book.getStock() - cartItem.getCount());//库存减少

            bookDao.updateBook(book);

            cartItemDao.deleteCartById(cartItem.getId());//结账完成后要将购物车中的商品删除
        }

        return orderId;//返回一个订单编号
        //提交事务
        //conn.commit();
        //如果异常事务回滚
        //conn.rollback();
    }
}
